package com.hhkj.admin.sale.common.utils;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hhkj.admin.common.util.WechatAppUtil;
import com.ruoyi.common.config.AliYunConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.oss.AliYunOSSUtils;
import com.ruoyi.common.utils.oss.model.AliYunUploadResult;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * InvitationQRCodeUtils
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/10/26 16:09
 */
@Slf4j
public class InvitationQRCodeUtils {

    /**
     * 生成二维码
     *
     * @param saleNum 销售编号
     * @return 二维码url地址
     */
    public static String generateAliYunUrl(String saleNum) {
        if (StringUtils.isBlank(saleNum)) {
            log.info("销售编号为空，无法生成邀请码");
        }
        AliYunUploadResult aliYunUploadResult;
        String putKey;
        InputStream inputStream = null;
        try {
            inputStream = WechatAppUtil.generateQrCode(saleNum);
            putKey = AliYunConfig.getProjectRootFolderName()
                    + CharUtil.SLASH + WechatAppUtil.environment + CharUtil.SLASH + StringUtils.getRandomString(3) + saleNum + ".jpg";
            aliYunUploadResult = AliYunOSSUtils.uploadMultipartFileToOSS(inputStream, putKey);
        } catch (Exception e) {
            log.info("生成邀请失败，请及时处理");
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.info("邀请码输入流无法正常关闭");
                }
            }
        }
        if (ObjectUtil.isNull(aliYunUploadResult) || !aliYunUploadResult.isResultFlag()) {
            log.info("生成邀请失败，请及时处理");
            return null;
        }
        return AliYunConfig.getUrlPrefix() + putKey;
    }
}
